package com.xiaoshuidi.cloud.module.finance.service.invoice.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoshuidi.cloud.framework.common.exception.ErrorCode;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.contract.api.ContractApi;
import com.xiaoshuidi.cloud.module.contract.vo.FeesApiVo;
import com.xiaoshuidi.cloud.module.finance.controller.admin.collection.vo.FinanceCollectionConfigReqVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.collection.vo.FinanceCollectionConfigRespVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.invoice.vo.FinanceInvoiceFeeTaxReqVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.invoice.vo.FinanceInvoiceTaxRateVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.invoice.vo.FinanceInvoiceTitleConfigReqVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.invoice.vo.FinanceInvoiceTitleConfigRespVO;
import com.xiaoshuidi.cloud.module.finance.convert.collection.FinanceCollectionConfigConvert;
import com.xiaoshuidi.cloud.module.finance.convert.finance.InvoiceConvert;
import com.xiaoshuidi.cloud.module.finance.convert.invoice.FinanceInvoiceTitleConfigConvert;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.collection.FinanceCollectionConfigDO;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.invoice.FinanceInvoiceTaxRateDO;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.invoice.FinanceInvoiceTitleConfigDO;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.collection.FinanceCollectionConfigMapper;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.invoice.FinanceInvoiceTaxRateMapper;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.invoice.FinanceInvoiceTitleConfigMapper;
import com.xiaoshuidi.cloud.module.finance.enums.finance.PayChannelTypeEnum;
import com.xiaoshuidi.cloud.module.finance.service.collection.FinanceCollectionConfigService;
import com.xiaoshuidi.cloud.module.finance.service.invoice.FinanceInvoiceConfigService;
import com.xiaoshuidi.cloud.module.finance.service.invoice.FinanceInvoiceTitleConfigService;
import com.xiaoshuidi.cloud.module.system.api.apartment.ApartmentManageApi;
import com.xiaoshuidi.cloud.module.system.enums.apartment.ApartmentManageEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FinanceInvoiceTitleConfigServiceImpl implements FinanceInvoiceTitleConfigService {

    @Resource
    private FinanceInvoiceTitleConfigMapper financeInvoiceTitleConfigMapper;
    @Resource
    private ApartmentManageApi apartmentManageApi;
    @Resource
    FinanceInvoiceTaxRateMapper financeInvoiceTaxRateMapper;
    @Resource
    ContractApi contractApi;
    /**
     * 获取配置信息
     *
     * @param apartmentId
     * @return
     */
    @Override
    public FinanceInvoiceTitleConfigRespVO get(Long apartmentId) {
        FinanceInvoiceTitleConfigDO financeInvoiceTitleConfigDO = financeInvoiceTitleConfigMapper.selectOne(FinanceInvoiceTitleConfigDO::getApartmentId, apartmentId);
        if (Objects.nonNull(financeInvoiceTitleConfigDO)){
            FinanceInvoiceTitleConfigRespVO respVO = FinanceInvoiceTitleConfigConvert.INSTANCE.convert(financeInvoiceTitleConfigDO);
            List<FinanceInvoiceTaxRateDO> taxes = financeInvoiceTaxRateMapper.selectList("invoice_config_id",financeInvoiceTitleConfigDO.getId().intValue());
            if(CollectionUtils.isNotEmpty(taxes)){
                respVO.setTaxes(InvoiceConvert.INSTANCE.convertToList2(taxes));
            }
            return respVO;
        }
        return null;
    }


    /**
     * 保存配置信息
     *
     * @param financeInvoiceTitleConfigReqVO
     */
    @Override
    public void save(FinanceInvoiceTitleConfigReqVO financeInvoiceTitleConfigReqVO) {
        //校验参数
        FinanceInvoiceTitleConfigDO financeInvoiceTitleConfigDO = financeInvoiceTitleConfigMapper.selectOne(FinanceInvoiceTitleConfigDO::getApartmentId, financeInvoiceTitleConfigReqVO.getApartmentId());
        //不存在就初始化，存在做保存操作
        if (financeInvoiceTitleConfigDO == null){
            FinanceInvoiceTitleConfigDO convert = FinanceInvoiceTitleConfigConvert.INSTANCE.convert(financeInvoiceTitleConfigReqVO);
            financeInvoiceTitleConfigMapper.insert(convert);
            //更改门店配置状态
            apartmentManageApi.updateApartment(financeInvoiceTitleConfigReqVO.getApartmentId(), ApartmentManageEnum.INVOICE_CONFIG.getCode());
            return;
        }
        FinanceInvoiceTitleConfigDO updateConfig = FinanceInvoiceTitleConfigConvert.INSTANCE.convert(financeInvoiceTitleConfigReqVO);
        updateConfig.setId(financeInvoiceTitleConfigDO.getId());
        financeInvoiceTitleConfigMapper.updateById(updateConfig);
        //费项明细
        financeInvoiceTaxRateMapper.delete(new QueryWrapper<FinanceInvoiceTaxRateDO>()
                .eq("invoice_config_id", financeInvoiceTitleConfigDO.getId().intValue()));
        Long tenantId = Objects.requireNonNull(SecurityFrameworkUtils.getLoginUser()).getTenantId();
        List<FeesApiVo> fees = contractApi.getConfigFees(tenantId).getCheckedData();
        log.info("{}", JSONObject.toJSONString(fees));
        if (CollectionUtils.isNotEmpty(fees)){
            Map<Integer,FinanceInvoiceTaxRateVO> taxes = new HashMap<>();
            Map<Long, List<FeesApiVo>> map = fees.stream().collect(Collectors.groupingBy(FeesApiVo::getFeeTypeId));
            log.info("{}", JSONObject.toJSONString(map));
            for (FinanceInvoiceTaxRateVO tax : financeInvoiceTitleConfigReqVO.getTaxes()) {
                List<FeesApiVo> list = map.get(tax.getFeeId().longValue());
                log.info("{} {}", JSONObject.toJSONString(tax), JSONObject.toJSONString(list));
                if(CollectionUtils.isNotEmpty(list)){
                    for (FeesApiVo f : list){
                        FinanceInvoiceTaxRateVO vo = new FinanceInvoiceTaxRateVO();
                        BeanUtils.copyProperties(tax, vo);
                        vo.setFeeId(f.getId());
                        taxes.put(f.getId(), vo);
                    }
                }
            }
            financeInvoiceTitleConfigReqVO.setTaxes(new ArrayList<>(taxes.values()));
        }
        List<FinanceInvoiceTaxRateDO> l = InvoiceConvert.INSTANCE.convertToList(financeInvoiceTitleConfigReqVO.getTaxes());
        l.forEach(t -> t.setInvoiceConfigId(financeInvoiceTitleConfigDO.getId().intValue()));
        financeInvoiceTaxRateMapper.insertBatch(l);
    }


}
